'use client';

import React from 'react';
import { Layout, Dropdown, Space, Avatar, message } from 'antd';
import { UserOutlined, LogoutOutlined, SettingOutlined, TeamOutlined, SafetyOutlined } from '@ant-design/icons';
import { useRouter } from 'next/navigation';
import type { MenuProps } from 'antd';
import Image from 'next/image';
import styles from '../Admin.module.scss';
import { useConfig } from '../../../utils/useConfig';
import { useAuth } from '../../../contexts/AuthContext';

const { Header } = Layout;

const AdminHeader: React.FC = () => {
  const router = useRouter();
  const { config, loading } = useConfig();
  const { user, logout, isAuthenticated } = useAuth();
  
  // 从配置中读取系统标题，如果加载中则显示默认值
  const systemTitle = config?.title || 'AIGC教学设计平台';
  const username = user?.displayName || user?.username || '未登录';

  /**
   * 退出登录
   */
  const handleLogout = async () => {
    try {
      await logout();
      router.push('/login');
    } catch (error) {
      console.error('登出失败:', error);
      message.error('登出失败，请稍后重试');
    }
  };

  /**
   * 跳转到个人设置
   */
  const handleSettings = () => {
    router.push('/profile');
  };

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'users',
      label: '用户列表',
      icon: <UserOutlined />,
      onClick: () => router.push('/admin/users'),
    },
     {
      type: 'divider',
    },
    {
      key: 'roles',
      label: '角色管理',
      icon: <SafetyOutlined />,
      onClick: () => router.push('/admin/roles'),
    },
     {
      type: 'divider',
    },
    {
      key: 'permissions',
      label: '权限管理',
      icon: <SettingOutlined />,
      onClick: () => router.push('/admin/permissions'),
    },
    {
      type: 'divider',
    },
    {
      key: 'settings',
      label: '个人设置',
      icon: <SettingOutlined />,
      onClick: handleSettings,
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ];

  // 如果未认证，显示登录提示
  if (!isAuthenticated) {
    return (
      <Header className={styles.adminHeader}>
        <div className={styles.headerLeft}>
          <div className={styles.logo}>
            <Image
              src="/logo.png"
              alt="Logo"
              width={32}
              height={32}
              priority
            />
          </div>
          <span className={styles.title}>{systemTitle}</span>
        </div>
        <div className={styles.headerRight}>
          <Space>
            <span 
              className={styles.username}
              onClick={() => router.push('/login')}
              style={{ cursor: 'pointer' }}
            >
              请先登录
            </span>
            <Avatar 
              icon={<UserOutlined />} 
              size="small" 
              onClick={() => router.push('/login')}
              style={{ cursor: 'pointer' }}
            />
          </Space>
        </div>
      </Header>
    );
  }

  return (
    <Header className={styles.adminHeader}>
      <div className={styles.headerLeft}>
        <div className={styles.logo}>
          <Image
            src="/logo.png"
            alt="Logo"
            width={32}
            height={32}
            priority
          />
        </div>
        <span className={styles.title}>{systemTitle}</span>
      </div>

      <div className={styles.headerRight}>
        <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
          <div className={styles.userInfo}>
            <Space>
              <Avatar 
                src={user?.avatar} 
                icon={<UserOutlined />} 
                size="small" 
              />
              <span className={styles.username}>{username}</span>
              {user?.role === 'admin' && (
                <span className={styles.roleTag}>管理员</span>
              )}
            </Space>
          </div>
        </Dropdown>
      </div>
    </Header>
  );
};

export default AdminHeader;